/**
 * 
 */
package org.jenkon.map;

import java.util.Map;

import org.jenkon.decorator.MapDecorator;
import org.jenkon.utils.ClassUtils;

/**
 * {@link MapDecorator} implementation, to merge many maps to only one {@link Map}.
 * 
 * @author Jens Konopka
 * 
 * @param <K> type of key
 * @param <V> type of value
 */
public class MergableMap<K, V> extends MapDecorator<K, V> {

	/**
	 * @param map the decorating {@link Map}.
	 */
	public MergableMap(final Map<K, V> map) {
		super(map);
	}

	/**
	 * Merge this with the array with {@link Map} objects to only one {@link Map}. Loop over all
	 * maps and her entries and check of the key exist in this. If the key doesn't exist in this,
	 * then put the entry to result {@link Map}.
	 * 
	 * @param maps array of {@link Map} objects to merge.
	 * @return {@link Map} with the result of all.
	 */
	public Map<K, V> merge(final Map<K, V>... maps) {
		final Map<K, V> results = ClassUtils.newInstance(map);
		results.putAll(map);
		for (final Map<K, V> entity : maps) {
			for (final Map.Entry<K, V> entry : entity.entrySet()) {
				if (!results.containsKey(entry.getKey())) {
					results.put(entry.getKey(), entry.getValue());
				}
			}
		}
		return results;
	}

}
